package com.niiwoo.civet.trade.service.local.contract;

import com.alibaba.fastjson.JSON;
import com.niiwoo.civet.trade.dao.entity.FadadaContractTemplateFile;
import com.niiwoo.civet.trade.dao.entity.Project;
import com.niiwoo.civet.trade.dao.entity.ProjectContract;
import com.niiwoo.civet.trade.dao.mapper.FadadaContractTemplateFileMapperExt;
import com.niiwoo.civet.trade.dao.mapper.ProjectContractMapperExt;
import com.niiwoo.civet.trade.dao.mapper.ProjectMapperExt;
import com.niiwoo.civet.trade.enums.FadadaContractEnum;
import com.niiwoo.civet.trade.enums.FadadaContractTemplateEnum;
import com.niiwoo.tripod.provider.exception.BizException;
import com.niiwoo.tripod.service.component.SnowflakeIdWorker;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @Author: wuke
 * @Description: 代扣合同（还款服务委托书）业务处理类
 * @Date: Created in 10:07 2017/12/7
 */
@Slf4j
@Service
public class WithholdContractService {
    @Autowired
    private FadadaContractTemplateFileMapperExt contractTemplateFileMapper;
    @Autowired
    private ProjectContractMapperExt projectContractMapper;
    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;
    @Autowired
    private ProjectMapperExt projectMapperExt;

    @Autowired
    private FadadaContractContext fadadaContractContext;

    @Autowired
    private ProjectContractMapperExt projectContractMapperExt;

    /**
     * 企业代扣合同
     * @param project
     * @param userId
     * @throws Exception
     */
    public void companyWithhold(Project project, String userId) throws Exception {
        ProjectContract fastLoanInitContract = projectContractMapperExt.queryProjectContractByProjectIdAndContractType(project.getProjectId(), FadadaContractTemplateEnum.TemplateTypeEnum.COMPANY_WITHHOLD.getType());
        if (fastLoanInitContract == null) {
            String contractNo = String.valueOf(snowflakeIdWorker.nextId());
            fastLoanInitContract = fadadaContractContext.initContractRecord(project.getProjectId(),
                    userId, contractNo, FadadaContractTemplateEnum.TemplateTypeEnum.COMPANY_WITHHOLD.getType(),
                    FadadaContractEnum.TradeTypeEnum.LOAN.getType(), project.getProjectId());
            ((WithholdContractService) AopContext.currentProxy()).saveLendContractInitData(fastLoanInitContract);
        }
        if (StringUtils.isBlank(fastLoanInitContract.getViewUrl()) && StringUtils.isBlank(fastLoanInitContract.getDownloadUrl())) {
            ProjectContract fastLoanSignContract = fadadaContractContext.contractHandler(FadadaContractTemplateEnum.TemplateTypeEnum.COMPANY_WITHHOLD,
                    null, project, userId);

            fastLoanSignContract.setId(fastLoanInitContract.getId());
            ((WithholdContractService) AopContext.currentProxy()).updateProjectContract(fastLoanSignContract);
        }
    }
    @Transactional
    public void updateProjectContract(ProjectContract projectContract) {
        projectContractMapperExt.updateByPrimaryKeySelective(projectContract);
    }

    @Transactional
    public void saveLendContractInitData(ProjectContract projectContract) {
        projectContractMapperExt.insertSelective(projectContract);
    }

    public String getContractTemplateId(){
        String logHead = "WithholdContractService.getContractTemplateId ";
        FadadaContractTemplateFile contractTemplateFile = contractTemplateFileMapper.queryFadadaContractTemplateFileByTemplateType(FadadaContractTemplateEnum.TemplateTypeEnum.WITHHOLD.getType());
        log.info(logHead+"contractTemplateFile="+JSON.toJSONString(contractTemplateFile));
        if (contractTemplateFile == null) {
            log.error(logHead+"noWithholdContractTemplate还款服务委托书合同模板不存在");
            throw new BizException("TRD50002","还款服务委托书合同模板不存在");
        }
        return contractTemplateFile.getTemplateId();
    }
    public String getKaolaWithholdContractTemplateId(){
        String logHead = "WithholdContractService.getContractTemplateId ";
        FadadaContractTemplateFile contractTemplateFile = contractTemplateFileMapper.queryFadadaContractTemplateFileByTemplateType(FadadaContractTemplateEnum.TemplateTypeEnum.KAOLA_WITHHOLD.getType());
        log.info(logHead+"contractTemplateFile="+JSON.toJSONString(contractTemplateFile));
        if (contractTemplateFile == null) {
            log.error(logHead+"noWithholdContractTemplate还款服务委托书合同模板不存在");
            throw new BizException("TRD50002","还款服务委托书合同模板不存在");
        }
        return contractTemplateFile.getTemplateId();
    }


    @Transactional(rollbackFor = Exception.class)
    public void contractInfoSave(String userId, Long projectId, String templateId, String contractNo){
        ProjectContract projectContract = projectContractMapper.queryProjectContractByUserIdAndContractNo(userId, contractNo);
        Date now = new Date();
        if(projectContract==null){ //新增
            projectContract = new ProjectContract();
            projectContract.setId(snowflakeIdWorker.nextId());
            projectContract.setTemplateId(templateId);
            projectContract.setProjectId(projectId);
            projectContract.setUserId(userId);
            projectContract.setContractNo(contractNo);
            projectContract.setTransactionId(contractNo);
            projectContract.setContractType(FadadaContractEnum.ContractTypeEnum.WITHHOLD.getType()); //合同类型：1、借款,2、代扣,3、团贷网发标,4、反担保,5、仲裁,6、送达回证,7.考拉法大大债仅转让合同
            projectContract.setTradeType(FadadaContractEnum.TradeTypeEnum.LOAN.getType()); //交易类型：（1借款 2担保 3 投资）
            projectContract.setOrderId(projectId);
            projectContract.setStatus(FadadaContractEnum.StatusEnum.NO.getStatus()); //0未签，1已签合同
            projectContract.setIsAuto(FadadaContractEnum.IsAutoEnum.AUTO.getType()); //0手动，1自动
            projectContract.setCreateTime(now);
            projectContract.setUpdateTime(now);
            projectContractMapper.insertSelective(projectContract);
        }else{ //更新
            projectContract.setTemplateId(templateId);
            projectContract.setProjectId(projectId);
            projectContract.setUserId(userId);
            projectContract.setContractNo(contractNo);
            projectContract.setTransactionId(contractNo);
            projectContract.setContractType(FadadaContractEnum.ContractTypeEnum.WITHHOLD.getType()); //合同类型：1、借款,2、代扣,3、团贷网发标,4、反担保,5、仲裁,6、送达回证,7.考拉法大大债仅转让合同
            projectContract.setTradeType(FadadaContractEnum.TradeTypeEnum.LOAN.getType()); //交易类型：（1借款 2担保 3 投资）
            projectContract.setOrderId(projectId);
            projectContract.setStatus(FadadaContractEnum.StatusEnum.NO.getStatus()); //0未签，1已签合同
            projectContract.setIsAuto(FadadaContractEnum.IsAutoEnum.AUTO.getType()); //0手动，1自动
            projectContract.setUpdateTime(now);
            projectContractMapper.updateByUserIdContractNoSelective(projectContract);
        }
    }
    @Transactional(rollbackFor = Exception.class)
    public void kaolaContractInfoSave(String userId, Long projectId, String templateId, String contractNo){
        ProjectContract projectContract = projectContractMapper.queryProjectContractByUserIdAndContractNo(userId, contractNo);
        Date now = new Date();
        if(projectContract==null){ //新增
            projectContract = new ProjectContract();
            projectContract.setId(snowflakeIdWorker.nextId());
            projectContract.setTemplateId(templateId);
            projectContract.setProjectId(projectId);
            projectContract.setUserId(userId);
            projectContract.setContractNo(contractNo);
            projectContract.setTransactionId(contractNo);
            projectContract.setContractType(FadadaContractEnum.ContractTypeEnum.KAOLA_WITHHOLD.getType()); //合同类型：1、借款,2、代扣,3、团贷网发标,4、反担保,5、仲裁,6、送达回证,7.考拉法大大债仅转让合同
            projectContract.setTradeType(FadadaContractEnum.TradeTypeEnum.LOAN.getType()); //交易类型：（1借款 2担保 3 投资）
            projectContract.setOrderId(projectId);
            projectContract.setStatus(FadadaContractEnum.StatusEnum.NO.getStatus()); //0未签，1已签合同
            projectContract.setIsAuto(FadadaContractEnum.IsAutoEnum.AUTO.getType()); //0手动，1自动
            projectContract.setCreateTime(now);
            projectContract.setUpdateTime(now);
            projectContractMapper.insertSelective(projectContract);
        }else{ //更新
            projectContract.setTemplateId(templateId);
            projectContract.setProjectId(projectId);
            projectContract.setUserId(userId);
            projectContract.setContractNo(contractNo);
            projectContract.setTransactionId(contractNo);
            projectContract.setContractType(FadadaContractEnum.ContractTypeEnum.KAOLA_WITHHOLD.getType()); //合同类型：1、借款,2、代扣,3、团贷网发标,4、反担保,5、仲裁,6、送达回证,7.考拉法大大债仅转让合同
            projectContract.setTradeType(FadadaContractEnum.TradeTypeEnum.LOAN.getType()); //交易类型：（1借款 2担保 3 投资）
            projectContract.setOrderId(projectId);
            projectContract.setStatus(FadadaContractEnum.StatusEnum.NO.getStatus()); //0未签，1已签合同
            projectContract.setIsAuto(FadadaContractEnum.IsAutoEnum.AUTO.getType()); //0手动，1自动
            projectContract.setUpdateTime(now);
            projectContractMapper.updateByUserIdContractNoSelective(projectContract);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void contractSignSuccessDataDeal(String userId, String contractNo,String downloadUrl,String viewUrl){
        ProjectContract projectContract = projectContractMapper.queryProjectContractByUserIdAndContractNo(userId, contractNo);
        Date now = new Date();
        projectContract.setStatus(FadadaContractEnum.StatusEnum.YES.getStatus()); //0未签，1已签合同
        projectContract.setDownloadUrl(downloadUrl);
        projectContract.setViewUrl(viewUrl);
        projectContract.setUpdateTime(now);
        projectContractMapper.updateByUserIdContractNoSelective(projectContract);
    }
    public List<Project> queryUserSignConstract(List<String> userIdList, byte status, String channelCode){
        List<Project> projectList = projectMapperExt.queryUserSignConstract(status,channelCode,userIdList);
        return projectList;
    }
}
